package com.xxcxcxcx.jobsystem.common.inits;

import com.xxcxcxcx.jobsystem.Main;
import com.xxcxcxcx.jobsystem.common.capability.JobCapability;
import com.xxcxcxcx.jobsystem.common.capability.JobCapabilityProvider;
import net.minecraft.resources.ResourceLocation;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.entity.Entity;
import net.minecraft.world.entity.player.Player;
import net.minecraftforge.common.capabilities.RegisterCapabilitiesEvent;
import net.minecraftforge.event.AttachCapabilitiesEvent;
import net.minecraftforge.event.entity.player.PlayerEvent;
import net.minecraftforge.eventbus.api.SubscribeEvent;
import net.minecraftforge.fml.common.Mod;

@Mod.EventBusSubscriber
public class CapabilityInit {
    @SubscribeEvent
    public static void onRegisterCapabilities(RegisterCapabilitiesEvent event) {
        event.register(JobCapability.class);
    }

    @SubscribeEvent
    public static void onAttachCapabilitiesPlayer(AttachCapabilitiesEvent<Entity> event) {
        if(event.getObject() instanceof Player) {
            if(!event.getObject().getCapability(JobCapabilityProvider.CAPABILITY).isPresent()) {
                event.addCapability(new ResourceLocation(Main.MOD_ID, "job_cap"), new JobCapabilityProvider((Player) event.getObject()));
            }
        }
    }

    /**
     * 当玩家死亡或传送时拷贝Capability
     */
    @SubscribeEvent
    public static void onPlayerCloned(PlayerEvent.Clone event) {
        /*Player player = event.getPlayer();
        if(player.level instanceof ServerLevel) {

        }*/
        if(event.isWasDeath()) {
            event.getOriginal().reviveCaps();
            JobCapabilityProvider.getPlayerData(event.getOriginal()).ifPresent(oldStore -> {
                JobCapabilityProvider.getPlayerData(event.getPlayer()).ifPresent(newStore -> {
                    newStore.deserializeNBT(oldStore.serializeNBT());
                });
            });
            event.getOriginal().invalidateCaps();
        }
    }
}
